package com.swift.utils;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.swift.R;
import com.swift.bean.UpdateInfo;
import com.swift.inteface.ICheckUpdate;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author coolszy
 * @date 2012-4-26
 * @blog http://blog.92coding.com
 */

public class UpdateManager {
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /*需要更新*/
    private static final int SHOW_UPDATE_DIALOG = 3;
    /*显示信息*/
    private static final int SHOW_UNUPDATE_MSG = 4;
    /* 保存解析的XML信息 */
    UpdateInfo mUpdateInfo;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private TextView mPercentView;
    private Dialog mDownloadDialog;
    /*获取版本信息的URL*/
    private String mUrl;

    private Boolean mIsNeedUpdate;

    ICheckUpdate mICheckUpdate;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    mPercentView.setText(Integer.toString(progress) + "%");
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                case SHOW_UPDATE_DIALOG:
                    showNoticeDialog();
                    break;
                case SHOW_UNUPDATE_MSG:
                    //Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(Context context, String url) {
        this.mContext = context;
        this.mUrl = url + "/name/" + mContext.getPackageName();
        this.mIsNeedUpdate = null;
    }

    /**
     * 检测软件更新
     */
    public void Update(ICheckUpdate iCheckUpdate) {
        mICheckUpdate = iCheckUpdate;
        new Thread(new Runnable() {
            @Override
            public void run() {
                mIsNeedUpdate = false;
                int versionCode = getVersionCode(mContext);
                String verInfos = SysUtils.getHttpGetResult(mUrl, 5000);
                if (verInfos != null) {
                    try {
                        JSONObject jnb = new JSONObject(verInfos);
                        mUpdateInfo = new UpdateInfo();
                        mUpdateInfo.Url = jnb.getString("url");
                        mUpdateInfo.Name = jnb.getString("name");
                        mUpdateInfo.Version = jnb.getInt("version");
                        mIsNeedUpdate = versionCode < mUpdateInfo.Version;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (mIsNeedUpdate) {
                    mHandler.obtainMessage(SHOW_UPDATE_DIALOG).sendToTarget();
                } else {
                    mHandler.obtainMessage(SHOW_UNUPDATE_MSG).sendToTarget();
                }
            }
        }).start();
    }


    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1;

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(R.string.soft_update_info);
        // 更新
        builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                {
                   if (mICheckUpdate != null)
                   {
                       mICheckUpdate.checkUpdate();
                   }
                   else
                   {
                       Toast.makeText(mContext,"更新出现异常",Toast.LENGTH_SHORT).show();
                   }
                }

                else
                {
                    // 显示下载对话框
                    showDownloadDialog();
                }

            }
        });
        // 稍后更新
        builder.setNegativeButton(R.string.soft_update_later, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 显示软件下载对话框
     */
    public void showDownloadDialog() {
        // 构造软件下载对话框
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_updating);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        mPercentView = (TextView) v.findViewById(R.id.tv_percent);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        // 现在文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    mSavePath = Environment.getExternalStorageDirectory() + "/jiyi/apk";
                    URL url = new URL(mUpdateInfo.Url);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    File apkFile = new File(mSavePath, mUpdateInfo.Name);
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    }

    ;

    /**
     * 安装APK文件
     */
    private void installApk() {
//		File apkfile = new File(mSavePath, mUpdateInfo.Name);
//		if (!apkfile.exists())
//		{
//			return;
//		}
//		// 通过Intent安装APK文件
//		Intent i = new Intent(Intent.ACTION_VIEW);
//		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
//		mContext.startActivity(i);

        File apkfile = new File(mSavePath, mUpdateInfo.Name);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(mContext, "com.swift.maintenance.updateprovider", apkfile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile),
                    "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
    }



}
